<?php

namespace app\admin\controller\mycurrency\agent;

use app\common\controller\Backend;
use app\common\model\mycurrency\AgentMoneylog;
use app\common\model\mycurrency\AgentMoneyWithdrawal;
use app\common\model\mycurrency\Payment;
use app\common\model\User;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户-余额-提现管理
 *
 * @icon fa fa-circle-o
 */
class Moneywithdrawal extends Backend
{

    /**
     * Moneywithdrawal模型对象
     * @var \app\admin\model\mycurrency\agent\Moneywithdrawal
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mycurrency\agent\Moneywithdrawal;
        $this->view->assign("paymentModeList", $this->model->getPaymentModeList());
        $this->view->assign("statusList", $this->model->getStatusList());

        $this->assignconfig('toexamine', $this->auth->check('mycurrency/agent/moneywithdrawal/toexamine')); //审核权限
        $this->assignconfig('offlinePayment', $this->auth->check('mycurrency/agent/moneywithdrawal/offlinePayment')); //线下打款
        $this->assignconfig('payement', $this->auth->check('mycurrency/agent/moneywithdrawal/payement')); //线上打款
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['agent'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','money','witserpro','service_charge','actual_payment','payment_mode','explain','status','operation_explain','applytime','rejecttime','toexaminttime','paymenttime','createtime','updatetime']);
                $row->visible(['agent']);
				$row->getRelation('agent')->visible(['fullname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 审核
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function toexamine($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if ($params['status'] == AgentMoneyWithdrawal::STATUS_SHENHETONGGUO){
            $params['toexaminttime'] = time();
        }else if($params['status'] == AgentMoneyWithdrawal::STATUS_BOHUI){
            $params['rejecttime'] = time();
        }else{
            $this->error('审核状态错误');
        }
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            if($result == true){
                if($params['status'] == AgentMoneyWithdrawal::STATUS_BOHUI){//审核驳回
                    //提现金额退回代理商余额
                    AgentMoneylog::moneyChange($row->agent_id,$row->money,AgentMoneylog::TYPE_TIXIANBOHUI,[
                        'memo' => '代理商提现申请驳回：' . $params['operation_explain'],
                        'withdrawal_id' => $row->id,
                    ]);
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 线下打款
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function offlinepayment($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['status'] = AgentMoneyWithdrawal::STATUS_YIDAKUAN;
        $params['paymenttime'] = time();
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 线上打款
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function payement($ids = null)
    {
        $withdrawal = $this->model->get($ids);
        if(!$withdrawal){
            $this->error('提现记录不存在');
        }
        if($withdrawal['status'] != AgentMoneyWithdrawal::STATUS_SHENHETONGGUO){
            $this->error('提现记录不是待打款状态');
        }
        $agent = \app\common\model\mycurrency\Agent::where(['id' => $withdrawal['agent_id']])->find();
        $agent_user = User::get($agent['user_id']);
        Db::startTrans();
        try {
            //生成打款记录
            Payment::increase(Payment::WIHDRAWAL_TYPE_DAILISHANGTIXIAN,$agent_user['id'],$withdrawal['actual_payment'],$withdrawal['payment_mode'],[
                'agent_money_withdrawal_id' => $withdrawal['id'],
            ]);
            $withdrawal->status = AgentMoneyWithdrawal::STATUS_DAKUANZHONG;
            $withdrawal->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('申请打款成功');
    }

}
